package us.kg.kotoriforest.rr;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;

/**
 * ClassName: us.kg.kotoriforest.rr.Servlet2 </br>
 * Description: File Description
 *
 * @author Kotori rotroutine@163.com
 * @since 2024/11/29
 */
@WebServlet("/rr/Servlet2")
public class Servlet2 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html");
        try (ServletOutputStream outputStream = resp.getOutputStream()) {
            // 获取键值对类型的参数
            // 根据 key 值获取单个 value 值
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            outputStream.print("<h1>" + username + " : " + password + "</h1></br>");

            // 根据 key 值获取多个 value 值
            String[] hobbies = req.getParameterValues("hobby");
            outputStream.print("<h1>" + Arrays.toString(hobbies) + "</h1></br>");

            // 获取所有的参数名
            Enumeration<String> parameterNames = req.getParameterNames();
            while (parameterNames.hasMoreElements()) {
                String hobby = parameterNames.nextElement();
                // 因为可能同时含有一对一和一对多的键值对 所以我们全当做一对多处理
                String[] values = req.getParameterValues(hobby);

                String res = "<h1>" + hobby + " : ";
                res += (1 == values.length ? values[0] : Arrays.toString(values));
                res += "</h1>";

                outputStream.print(res);
            }
            outputStream.print("</br>");

            // 获得所有参数和其对应值所组成的 map 集合
            Map<String, String[]> parameterMap = req.getParameterMap();
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                String key = entry.getKey();
                String[] values = entry.getValue();

                String res = "<h1>" + key + " : ";
                res += (1 == values.length ? values[0] : Arrays.toString(values));
                res += "</h1>";

                outputStream.print(res);
            }
        }
    }
}
